package com.property.demo.controller;

import com.property.demo.dto.ApiResponse;
import com.property.demo.model.Repair;
import com.property.demo.service.RepairService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@CrossOrigin
@RequestMapping("/api/repairs")
public class RepairController {

    @Autowired
    private RepairService repairService;

    // 获取所有维修请求（分页）
    @GetMapping
    public ResponseEntity<?> getAllRepairs(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long ownerId,
            @RequestParam(required = false) Long homeId,
            @RequestParam(required = false) String description,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type) {
        
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
            
            Page<Repair> repairsPage;
            if (ownerId != null || homeId != null || (description != null && !description.isEmpty()) || 
                (status != null && !status.isEmpty()) || (type != null && !type.isEmpty())) {
                repairsPage = repairService.findByFilters(ownerId, homeId, description, status, type, pageable);
            } else {
                repairsPage = repairService.findAll(pageable);
            }
            
            return ResponseEntity.ok(repairsPage);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 获取所有维修请求（不分页）
    @GetMapping("/all")
    public ResponseEntity<?> getAllRepairsNoPage() {
        try {
            List<Repair> repairs = repairService.findAll();
            return ResponseEntity.ok(repairs);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 根据ID获取维修请求
    @GetMapping("/{id}")
    public ResponseEntity<?> getRepairById(@PathVariable Long id) {
        try {
            Optional<Repair> repair = repairService.findById(id);
            if (repair.isPresent()) {
                return ResponseEntity.ok(repair.get());
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 创建维修请求
    @PostMapping
    public ResponseEntity<?> createRepair(@RequestBody Repair repair) {
        try {
            Repair savedRepair = repairService.save(repair);
            return ResponseEntity.ok(new ApiResponse(true, "维修请求创建成功", savedRepair));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 更新维修请求
    @PutMapping("/{id}")
    public ResponseEntity<?> updateRepair(@PathVariable Long id, @RequestBody Repair repairDetails) {
        try {
            Repair updatedRepair = repairService.update(id, repairDetails);
            if (updatedRepair != null) {
                return ResponseEntity.ok(new ApiResponse(true, "维修请求更新成功", updatedRepair));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }

    // 删除维修请求
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteRepair(@PathVariable Long id) {
        try {
            Optional<Repair> repair = repairService.findById(id);
            if (repair.isPresent()) {
                repairService.delete(id);
                return ResponseEntity.ok(new ApiResponse(true, "维修请求删除成功"));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 批量删除维修请求
    @DeleteMapping("/batch")
    public ResponseEntity<?> batchDeleteRepairs(@RequestBody List<Long> ids) {
        try {
            repairService.deleteAll(ids);
            return ResponseEntity.ok(new ApiResponse(true, "维修请求批量删除成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 根据业主ID获取维修请求
    @GetMapping("/owner/{ownerId}")
    public ResponseEntity<?> getRepairsByOwner(@PathVariable Long ownerId) {
        try {
            List<Repair> repairs = repairService.findByOwnerId(ownerId);
            return ResponseEntity.ok(repairs);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 根据房屋ID获取维修请求
    @GetMapping("/home/{homeId}")
    public ResponseEntity<?> getRepairsByHome(@PathVariable Long homeId) {
        try {
            List<Repair> repairs = repairService.findByHomeId(homeId);
            return ResponseEntity.ok(repairs);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
    
    // 根据状态或类型搜索维修请求
    @GetMapping("/search")
    public ResponseEntity<?> searchRepairs(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type) {
        try {
            List<Repair> repairs;
            if (status != null && !status.isEmpty()) {
                repairs = repairService.findByStatus(status);
            } else if (type != null && !type.isEmpty()) {
                repairs = repairService.findByType(type);
            } else {
                repairs = repairService.findAll();
            }
            return ResponseEntity.ok(repairs);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "处理请求时发生错误，请联系系统管理员"));
        }
    }
} 